package main

import (
	"flag"
	"net/http"
	"os"
	"pve_exporter/collector"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	log "github.com/sirupsen/logrus"
)

func init() {
	log.SetFormatter(&log.JSONFormatter{})
	log.SetOutput(os.Stdout)
	log.SetLevel(log.WarnLevel)
}

func getEnv(key string, defaultVal string) string {
	if envVal, ok := os.LookupEnv(key); ok {
		return envVal
	}
	return defaultVal
}

func main() {
	var passwordFile = flag.String("password-file", getEnv("PVE_PASSWORD_FILE", ""), "password file of the pve server to scrape")
	var port = flag.String("port", "8080", "listen port")
	flag.Parse()

	passwordMap := make(map[string]collector.UserInfo)
	var err error
	if *passwordFile != "" {
		passwordMap, err = collector.LoadPwdFile(*passwordFile)
		if err != nil {
			log.Fatalf("Error loading pve password from files %s, err:%s", *passwordFile, err)
		}
	}

	http.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
		target := r.URL.Query().Get("target")
		if target == "" {
			http.Error(w, "target parameter must be specified", http.StatusBadRequest)
			return
		}

		worker := collector.NewPveCollector(target, collector.Options{UserInfo: passwordMap[target]})
		reg := prometheus.NewPedanticRegistry()
		reg.MustRegister(worker)
		gatherers := prometheus.Gatherers{
			reg,
		}
		h := promhttp.HandlerFor(gatherers, promhttp.HandlerOpts{
			ErrorLog:      log.New(),
			ErrorHandling: promhttp.ContinueOnError,
		})
		h.ServeHTTP(w, r)
	})

	if err := http.ListenAndServe(":"+*port, nil); err != nil {
		os.Exit(1)
	}
}
